//#define __FORCE_TRACE__
//#define __FORCE_DEBUG__
//#define __FORCE_INFO__
#define THIS_FILE "tools\fn_respawnVehicle.sqf"
#include <tmf_constants.h>
#include <tmf_macros.h>

TRACE_1("Start",_this);
TMFPROFILERSTART;

private ["_unit","_respawn_timer","_unit_type","_init_pos","_init_dir","_time_empty","_max_respawns"];
DEFAULT_PARAM(_unit,0,objNull);
DEFAULT_PARAM(_respawn_timer,1,450);
DEFAULT_PARAM(_max_respawns,2,-1);

if (AND_ALSO((!isnull _unit),(IS_OBJECT(_unit)))) then {
	_time_empty = 0;
	if (typename _this == typename []) then {
		_unit = _this select 0;
		if (count _this > 1) then { _respawn_timer = _this select 1; };
	};
	OSETVAR(_unit,QGVAR(respawn_timer),_respawn_timer);
	_unit addEventHandler ["GetIn",{_vec = _this select 0; _timer = OGETVAR(_vec,QGVAR(respawn_timer),450); _unit = _this select 2; [QGVAR(all_message),[["STR_RESPAWN_VEC",_timer],"unit",_unit,"global"],THIS_FILE] call FFUNC(callEvent);}];
	_init_pos = getPos _unit;
	_init_dir = getDir _unit;
	_unit_type = typeof _unit;
	// We test the IsNull because it allows to stop the respawn script externally by deleting the unit.
	while {_max_respawns != 0 && !isnull _unit} do {
		if (!alive _unit) then {
			sleep 10;
			DEBUG_1("Respawning Destroyed Unit",ARR_2(_unit_type,_max_respawns));
			if (!isnull _unit) then { deleteVehicle _unit; };
			_unit = _unit_type createVehicle _init_pos;
			_unit setPos _init_pos;
			_unit setDir _init_dir;
			OSETVAR(_unit,QGVAR(respawn_timer),_respawn_timer);
			_unit addEventHandler ["GetIn",{_vec = _this select 0; _timer = OGETVAR(_vec,QGVAR(respawn_timer),450); _unit = _this select 2; [QGVAR(all_message),[["STR_RESPAWN_VEC",_timer],"unit",_unit,"global"],THIS_FILE] call FFUNC(callEvent);}];
			DEC(_max_respawns);
		} else {
			if ((_unit distance _init_pos) > 100) then {
				if (_time_empty > 0) then {
					if (count (crew _unit) > 0) then {
						_time_empty = 0;
					} else {
						if ((time - _time_empty) > _respawn_timer) then {
							DEBUG_1("Respawning Empty Unit",ARR_2(_unit_type, time));
							if (damage _unit > 0.4) then {
								_unit setPos [0,0,0];
								_unit setDamage 1;
							} else {
								_unit setPos _init_pos;
								_unit setDir _init_dir;
							};
						};
					};
				} else {
					if (count (crew _unit) <= 0) then {
						DEBUG_1("Detected Empty Unit",ARR_2(_unit_type, time));
						_time_empty = time;
					} else {
						_time_empty = 0;
					};
				};
			};
		};
		sleep (15 + random (15));
	};
} else {
	ERROR("Invalid Input");
};
TRACE("End");
TMFPROFILERSTOP;
